#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: clipboard.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: clipboard operations

from rdflib import URIRef
import gtk

from vazaarlib.namespaces import NIE

class ClipboardView():
    def __init__(self, gui):
        self.gui = gui
        self.gui.frontend['clp-container'] = self.gui.glade.widgets.get_widget("cntClipboard")
        self.operation = None
        self.selected = None

    def toggle_view(self):
        self.update_clipboard_view()
        if self.gui.frontend['sh-btnclp'].get_active():
            self.gui.frontend['sh-clipboard'].hide_all()
        else:
            self.gui.frontend['sh-clipboard'].set_no_show_all(False)
            self.gui.frontend['sh-clipboard'].show_all()



    def hide_window(self, *args):
        self.gui.frontend['col-window'].hide_all()

    def update_clipboard_view(self):
        query = """
                PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                PREFIX nfo: <http://www.semanticdesktop.org/ontologies/nfo/>
                PREFIX nie: <http://www.semanticdesktop.org/ontologies/nie/>

                SELECT ?id ?title
                WHERE
                {
                    ?id rdf:type nfo:Clipboard .
                    ?id nie:title ?title .
                }
                ORDER BY ASC(?title)
                """

        result = self.gui.ask.this(query)
        model = gtk.ListStore(str, gtk.gdk.Pixbuf, str)
        icon = self.gui.widget.render_icon(gtk.STOCK_PASTE, gtk.ICON_SIZE_DIALOG)
        for (id, title) in result.selected:
            #print id, title
            model.append((id, icon, title))
        self.treeview = gtk.TreeView()
        self.treeview.set_model(model)
        self.treeview.set_headers_visible(False)
        self.treeview.connect('row-activated', self.clipboard_selected)
        selection = self.treeview.get_selection()
        selection.set_mode(gtk.SELECTION_MULTIPLE)
        selection.unselect_all()


        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn('id', renderer, text=0)
        column.set_visible(False)
        self.treeview.append_column(column)

        renderer = gtk.CellRendererPixbuf()
        column = gtk.TreeViewColumn('', renderer, pixbuf=1)
        self.treeview.append_column(column)

        renderer = gtk.CellRendererText()
        #renderer.connect('edited', self.cell_edited_callback, model)
        #renderer.connect('editing-canceled', self.cell_editing_canceled, model)

        renderer.set_property('editable', True)

        column = gtk.TreeViewColumn('Title', renderer, text=2)
        self.treeview.append_column(column)
        self.treeview.show_all()
        container = gtk.ScrolledWindow()
        container.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        container.set_shadow_type(gtk.SHADOW_OUT)
        container.add(self.treeview)
        container.show_all()

        old = self.gui.frontend['clp-container'].get_children()
        if old:
            self.gui.frontend['clp-container'].remove(old[0])

        self.gui.frontend['clp-container'].add(container)
        self.gui.frontend['clp-container'].show_all()

    def update_clipboard_name(self):
        pass

    def clipboard_selected(self, iconview, path, view_column):
        pass

    def cell_editing_canceled(self, cell, model):
        print "editing canceled"

    def cell_edited_callback(self, cellrenderertext, path, new_text, model):
        iter = model.get_iter_from_string(str(path))
        id = model.get_value(iter, 0)
        if id == '-':
            title = new_text.decode('iso-8859-15')
            self.gui.app.vstore.create_new_clipboard(title)
        self.update_clipboard_view()

    def get_target(self, model, path, iter):
        # Add to source target list
        id = model.get_value(iter, 0)
        self.selected.append(id)

    def on_ok_callback(self, widget):
        if self.operation == 'add_to_clipboard':
            self.selected = []
            selection = self.treeview.get_selection()
            selection.selected_foreach(self.get_target)
            clipboards = self.selected
            resources = self.gui.frontend['target']
            for idres in resources:
                for idcol in clipboards:
                    #FIXME: don't access bbdd directly. Use VStore
                    # because vazaar must be notified of all changes in
                    # every single resource.
                    if idcol != idres:
                        self.gui.app.store.add_triple(URIRef(idcol), NIE['hasLogicalPart'], URIRef(idres))
        self.gui.actions.update_gui()
        self.hide_window()

    def on_help_callback(self, widget):
        print "on_ok_callback: not implemented"


